<?php
/**
 * Created by PhpStorm.
 * User: daimingkang
 * Date: 2018/6/22
 * Time: 上午10:27
 */

namespace App\Api\Controllers\Merchant;


use Alipayopen\Sdk\AopClient;
use Alipayopen\Sdk\Request\AlipayTradeCancelRequest;
use Alipayopen\Sdk\Request\AlipayTradeQueryRequest;
use App\Api\Controllers\AlipayOpen\PayController;
use App\Api\Controllers\BaseController;
use App\Api\Controllers\Config\AlipayIsvConfigController;
use App\Common\MerchantFuwu;
use App\Common\PaySuccessAction;
use App\Common\StoreDayMonthOrder;
use App\Common\UserGetMoney;
use App\Models\AlipayAccount;
use App\Models\AlipayAppOauthUsers;
use App\Models\AlipayHbOrder;
use App\Models\AlipayHbrate;
use App\Models\MerchantStore;
use App\Models\Store;
use App\Models\StorePayWay;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AliFqPayController extends BaseController
{

    //花呗分期支付
    public function fq_pay(Request $request)
    {
        try {
            $merchant = $this->parseToken();
            $merchant_id = $merchant->merchant_id;
            $merchant_name = $merchant->merchant_name;
            $shop_name = $request->get('shop_name', '分期商品');

            if ($shop_name == "undefined") {
                $shop_name = "分期商品";
            }

            $total_amount = $request->get('total_amount'); //金额
            $total_amount = number_format($total_amount, 2, '.', '');
            $shop_price = $request->get('shop_price', $total_amount);
            $hb_fq_num = (int)$request->get('hb_fq_num'); //花呗分期数
            $hb_fq_seller_percent = $request->get('hb_fq_seller_percent'); //商家承担手续费传入100，用户承担手续费传入0$hb_fq_seller_percent=0;
            $buyer_user = $request->get('buyer_user', '');
            $buyer_phone = $request->get('buyer_phone', '');
            $ways_source = $request->get('ways_source', ''); //支付通道
            $config_id = $merchant->config_id;
            $auth_code = $request->get('auth_code', '');
            $store_id = $request->get('store_id', '');
            $check_data = [
                'total_amount' => '总金额',
                'shop_price' => '商品金额',
                'hb_fq_num' => '分期数',
                'hb_fq_seller_percent' => '手续费承担方',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $data = [
                'merchant_id' => $merchant_id,
                'merchant_name' => $merchant_name,
                'shop_name' => $shop_name,
                'total_amount' => $total_amount,
                'shop_price' => $shop_price,
                'hb_fq_num' => $hb_fq_num,
                'hb_fq_seller_percent' => $hb_fq_seller_percent,
                'buyer_user' => $buyer_user,
                'buyer_phone' => $buyer_phone,
                'ways_source' => $ways_source,
                'config_id' => $config_id,
                'auth_code' => $auth_code,
                'store_id' => $store_id,

            ];

            return $this->fq_pay_public($data);


        } catch (\Exception $exception) {
            Log::info('花呗分期报错');
            Log::info($exception);
            $info = $exception->getMessage();
            return json_encode([
                'status' => 2,
                'message' => $info
            ]);
        }

    }


    //花呗分期支付
    public function fq_pay_public($data)
    {
        try {
            $merchant_id = $data['merchant_id'];
            $merchant_name = $data['merchant_name'];
            $shop_name = $data['shop_name'];
            $total_amount = $data['total_amount']; //金额
            $total_amount = number_format($total_amount, 2, '.', '');
            $shop_price = $data['shop_price'];
            $hb_fq_num = $data['hb_fq_num']; //花呗分期数
            $hb_fq_seller_percent = $data['hb_fq_seller_percent']; //商家承担手续费传入100，用户承担手续费传入0$hb_fq_seller_percent=0;
            $buyer_user = $data['buyer_user'];
            $buyer_phone = $data['buyer_phone'];
            $ways_source = $data['ways_source']; //支付通道
            $config_type = '01';
            $config_id = $data['config_id'];
            $auth_code = $data['auth_code'];
            $store_id = $data['store_id'];

            $check_data = [
                'total_amount' => '总金额',
                'shop_price' => '商品金额',
                'hb_fq_num' => '分期数',
                'hb_fq_seller_percent' => '手续费承担方',
            ];
            $check = $this->check_required($check_data, $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }


            $AlipayHbrate = AlipayHbrate::where('store_id', $store_id)->first();
            if (!$AlipayHbrate) {
                return json_encode([
                    'status' => 2,
                    'message' => '商户未设置分期手续费'
                ]);
            }

            $status = 'hb_fq_num_' . $hb_fq_num . '_status';
            if ($AlipayHbrate->$status == "00") {
                return json_encode([
                    'status' => 2,
                    'message' => '不支持' . $hb_fq_num . '期,请选择其他期数'
                ]);
            }

            if ($store_id == "") {
                $MerchantStore = MerchantStore::where('merchant_id', $merchant_id)
                    ->orderBy('created_at', 'asc')
                    ->first();
                if ($MerchantStore) {
                    $store_id = $MerchantStore->store_id;
                }
            }

            $store = Store::where('store_id', $store_id)->first();

            $tg_user_id = $store->user_id;
            $store_name = $store->store_name;
            $store_pid = $store->pid;


            //请求参数
            $data = [
                'config_id' => $config_id,
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
                'total_amount' => $total_amount,
                'shop_price' => $shop_price,
                'remark' => '',
                'device_id' => '',
                'open_id' => '',
                'config_type' => '01',
                'shop_name' => $shop_name,
                'shop_desc' => '',
                'store_name' => $store_name,
                'is_fq' => 1,
                'is_fq_data' => [
                    'hb_fq_num' => $hb_fq_num,
                    'hb_fq_seller_percent' => $hb_fq_seller_percent
                ]
            ];

            if ($ways_source == "") {
                $StorePayWay = StorePayWay::where('store_id', $store_id)
                    ->where('company', 'zft')
                    ->select('id')
                    ->first();
                if ($StorePayWay) {
                    $ways_source = 'zft';
                } else {
                    $ways_source = 'alipay';
                }
            }

            //官方支付宝当面付花呗分期
            if ($ways_source == "alipay") {
                $StorePayWay = StorePayWay::where('store_id', $store_id)
                    ->where('company', 'alipay')
                    ->select('rate')
                    ->first();

                if (!$StorePayWay) {
                    return json_encode([
                        'status' => 2,
                        'message' => '通道未开通'
                    ]);
                }

                $rate = $StorePayWay->rate;
                $trade_pay_rate = number_format($rate, 2, '.', '');//当面付费率

                // }
                /*******************商户贴息模式**********************/
                $shop_name = '门店分期购:' . $hb_fq_num . '期' . $shop_name;
                $desc = '门店分期购:' . $hb_fq_num . '期' . $shop_name;


                //交易手续费
                $pay_sxf = ($trade_pay_rate * $shop_price) / 100;


                //分期手续费
                $hb_query_rate = [
                    'store_id' => $store_id,
                    'hb_fq_seller_percent' => $hb_fq_seller_percent,
                    'shop_price' => $shop_price,
                    'hb_fq_num' => $hb_fq_num
                ];

                $hb_query_rate = $this->hb_query_rate($hb_query_rate, $AlipayHbrate);
                $xy_rate = $hb_query_rate['data']['xy_rate'];
                $hb_fq_sxf = $hb_query_rate['data']['hb_fq_sxf'];
                $hb_fq_sxf_z = $hb_query_rate['data']['hb_fq_sxf_z'];
                $data['total_amount'] = number_format($hb_query_rate['data']['pay_total_amount'], 2, '.', '');

                //商户实际净额
                $receipt_amount = $shop_price - $pay_sxf;

                //商户承担服务费
                if ($hb_fq_seller_percent == "100") {
                    $receipt_amount = $receipt_amount - $hb_fq_sxf;
                }


                //入库参数
                $data_insert = [
                    'user_id' => $tg_user_id,
                    'store_id' => $store_id,
                    'merchant_id' => $merchant_id,
                    'store_name' => $store_name,
                    'merchant_name' => $merchant_name,
                    'buyer_user' => $buyer_user,
                    'buyer_phone' => $buyer_phone,
                    'shop_name' => $shop_name,
                    'shop_desc' => $desc,
                    'total_amount' => $data['total_amount'],
                    'shop_price' => $shop_price,
                    'receipt_amount' => $receipt_amount,
                    'pay_status' => 2,
                    'pay_status_desc' => '等待支付',
                    'hb_fq_num' => $hb_fq_num,
                    'hb_fq_seller_percent' => $hb_fq_seller_percent,
                    'hb_fq_sxf' => $hb_fq_sxf, //$this->hb_fq_sxf($hb_fq_num, $total_amount, $hb_fq_seller_percent),
                    'xy_rate' => $xy_rate,
                    'total_amount_out' => '0.00',
                    'out_status' => 2,
                    'config_id' => $config_id,
                    'pay_sxf' => $pay_sxf, //支付手续费
                ];

                $pay_obj = new PayController();

                //配置
                $isvconfig = new AlipayIsvConfigController();

                $storeInfo = $isvconfig->alipay_auth_info($store_id, $store_pid);
                $out_user_id = $storeInfo->user_id;//商户的id
                $alipay_store_id = $storeInfo->alipay_store_id;
                $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);

                if (!$storeInfo) {
                    $msg = '支付宝授权信息不存在';
                    return [
                        'status' => 2,
                        'message' => $msg
                    ];

                }
		
                $data['code'] = $auth_code;
                $data['alipay_store_id'] = $alipay_store_id;
                $data['out_user_id'] = $out_user_id;
                $data['app_auth_token'] = $storeInfo->app_auth_token;
                $data['config'] = $config;
                $data['notify_url'] = url('/api/alipayopen/fq_pay_notify');


                //扫一扫分期
                if ($auth_code) {
                    $out_trade_no = 'fq_scan' . date('YmdHis', time()) . $merchant_id . rand(10000, 99999);

                    $data['out_trade_no'] = $out_trade_no;
                    //入库参数
                    $data_insert['ways_type'] = 1006;
                    $data_insert['ways_type_desc'] = '扫一扫分期';
                    $data_insert['ways_source'] = 'alipay';
                    $data_insert['ways_source_desc'] = '支付宝';
                    $data_insert['out_trade_no'] = $out_trade_no;

                    $insert_re = AlipayHbOrder::create($data_insert);
                    if (!$insert_re) {
                        return json_encode([
                            'status' => 2,
                            'message' => '订单未入库'
                        ]);
                    }

                    //转出入库
                    if ($hb_fq_sxf_z > 0) {
                        //结算入库
                        $updatedata = [
                            'trade_no' => '',
                            'config_id' => $config_id,
                            'order_settle_amount' => $hb_fq_sxf_z,
                            'store_id' => $store_id,
                            'user_id' => $tg_user_id,
                            'trans_out' => $config->alipay_pid,
                            'out_trade_no' => $out_trade_no,
                            'total_amount' => $total_amount,
                            'status' => '0',
                            'status_desc' => '等待支付',
                        ];
                        $this->insert_settle_order($updatedata);
                    }

                    if ($StorePayWay->pcredit == "00") {
                        $disable_pay_channels = 'credit_group';//禁用信用方式
                        $data['disable_pay_channels'] = $disable_pay_channels;
                    }

                    $return_array = $pay_obj->scan_pay($data);

                    if ($return_array['status'] == 1) {
                        AlipayHbOrder::where('out_trade_no', $out_trade_no)->update(
                            [
                                'trade_no' => $return_array['trade_no'],
                                'buyer_id' => $return_array['buyer_id'],
                                'buyer_logon_id' => $return_array['buyer_logon_id'],
                                'pay_status_desc' => '支付成功',
                                'pay_status' => 1,
                            ]);

                        //支付后
                        $gmt_payment = $return_array['pay_time'];

                        return json_encode([
                            'status' => 1,
                            'pay_status' => '1',
                            'message' => '支付成功',
                            'data' => [
                                'out_trade_no' => $out_trade_no,
                                'ways_type' => $data_insert['ways_type'],
                                'ways_source' => $data_insert['ways_source'],
                                'total_amount' => $total_amount,
                                'pay_amount' => $total_amount,
                                'store_id' => $store_id,
                                'store_name' => $store_name,
                                'config_id' => $config_id,
                                'pay_time' => $gmt_payment,
                                'ways_source_desc' => '花呗分期',
                        ]
                        ]);


                    }

                    if ($return_array['status'] == 3) {

                        return json_encode([
                            'status' => 1,
                            'pay_status' => '2',
                            'message' => '正在支付',
                            'data' => [
                                'out_trade_no' => $out_trade_no,
                                'ways_type' => $data_insert['ways_type'],
                                'ways_source' => $data_insert['ways_source'],
                                'total_amount' => $total_amount,
                                'pay_amount' => $total_amount,
                                'store_id' => $store_id,
                                'store_name' => $store_name,
                                'config_id' => $config_id,
                            ]
                        ]);
                    }

                    //其他状态
                    return json_encode($return_array);


                } else {
                    $data['notify_url'] = url('/api/alipayopen/fq_pay_notify');
                    $out_trade_no = 'fq_qr' . date('YmdHis', time()) . $merchant_id . rand(10000, 99999);
                    $data['out_trade_no'] = $out_trade_no;

                    if ($StorePayWay->credit == "00") {
                        $disable_pay_channels = 'credit_group';//禁用信用方式
                        $data['disable_pay_channels'] = $disable_pay_channels;
                    }

                    $return = $pay_obj->qr_pay($data);
                    $return_aray = json_decode($return, true);
                    if ($return_aray['status'] == 1) {
                        //入库参数
                        $data_insert['ways_type'] = 1007;
                        $data_insert['ways_type_desc'] = '固定二维码分期';
                        $data_insert['ways_source'] = 'alipay';
                        $data_insert['ways_source_desc'] = '支付宝';
                        $data_insert['out_trade_no'] = $out_trade_no;


                        $insert_re = AlipayHbOrder::create($data_insert);

                        if (!$insert_re) {
                            return json_encode([
                                'status' => 2,
                                'message' => '订单未入库'
                            ]);
                        }

                        //转出入库
                        if ($hb_fq_sxf_z > 0) {
                            //结算入库
                            $updatedata = [
                                'trade_no' => '',
                                'config_id' => $config_id,
                                'order_settle_amount' => $hb_fq_sxf_z,
                                'store_id' => $store_id,
                                'trans_out' => $config->alipay_pid,
                                'user_id' => $tg_user_id,
                                'out_trade_no' => $out_trade_no,
                                'total_amount' => $total_amount,
                                'status' => '0',
                                'status_desc' => '等待支付',
                            ];
                            $this->insert_settle_order($updatedata);
                        }
                    }
                }


                return $return;


            }


            //直付通花呗分期
            if ($ways_source == "zft") {
                $notify_url = url('/api/alipayopen/zft_fq_pay_notify');
                $StorePayWay = StorePayWay::where('store_id', $store_id)
                    ->where('company', 'zft')
                    ->select('rate')
                    ->first();

                if (!$StorePayWay) {
                    return json_encode([
                        'status' => 2,
                        'message' => '通道未开通'
                    ]);
                }

                $rate = $StorePayWay->rate;
                $trade_pay_rate = number_format($rate, 2, '.', '');//当面付费率

                /*******************商户贴息模式**********************/
                $shop_name = '门店分期购:' . $hb_fq_num . '期' . $shop_name;
                $desc = '门店分期购:' . $hb_fq_num . '期' . $shop_name;


                //交易手续费
                $pay_sxf = ($trade_pay_rate * $shop_price) / 100;

                //花呗分期服务费
                $hb_query_rate = [
                    'store_id' => $store_id,
                    'hb_fq_seller_percent' => $hb_fq_seller_percent,
                    'shop_price' => $shop_price,
                    'hb_fq_num' => $hb_fq_num
                ];
                $hb_query_rate = $this->hb_query_rate($hb_query_rate, $AlipayHbrate);
                $xy_rate = $hb_query_rate['data']['xy_rate'];
                $hb_fq_sxf = $hb_query_rate['data']['hb_fq_sxf'];
                $hb_fq_sxf_z = $hb_query_rate['data']['hb_fq_sxf_z'];
                $data['total_amount'] = number_format($hb_query_rate['data']['pay_total_amount'], 2, '.', '');


                //商户实际净额
                $receipt_amount = $shop_price - $pay_sxf;

                //商户承担服务费
                if ($hb_fq_seller_percent == "100") {
                    $receipt_amount = $receipt_amount - $hb_fq_sxf;
                }

                //入库参数
                $data_insert = [
                    'user_id' => $tg_user_id,
                    'store_id' => $store_id,
                    'merchant_id' => $merchant_id,
                    'store_name' => $store_name,
                    'merchant_name' => $merchant_name,
                    'buyer_user' => $buyer_user,
                    'buyer_phone' => $buyer_phone,
                    'shop_name' => $shop_name,
                    'shop_desc' => $desc,
                    'total_amount' => $shop_price,
                    'shop_price' => $shop_price,
                    'receipt_amount' => $receipt_amount,
                    'pay_status' => 2,
                    'pay_status_desc' => '等待支付',
                    'hb_fq_num' => $hb_fq_num,
                    'hb_fq_seller_percent' => $hb_fq_seller_percent,
                    'hb_fq_sxf' => $hb_fq_sxf, //$this->hb_fq_sxf($hb_fq_num, $total_amount, $hb_fq_seller_percent),
                    'xy_rate' => $xy_rate,
                    'total_amount_out' => '0.00',
                    'out_status' => 2,
                    'config_id' => $config_id,
                    'pay_sxf' => $pay_sxf,//支付手续费
                ];

                $pay_obj = new PayController();

                $config_type = '03';
                //配置
                $isvconfig = new AlipayIsvConfigController();
                $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);

                if (!$config) {
                    return json_encode([
                        'status' => 2,
                        'message' => '直付通配置不存在'
                    ]);
                }
                //判断直付通
                $AlipayZftStore = $isvconfig->AlipayZftStore($store_id, $store_pid);
                if (!$AlipayZftStore) {
                    return json_encode([
                        'status' => 2,
                        'message' => '直付通门店不存在'
                    ]);
                }

                $smid = $AlipayZftStore->smid;


                if (!$AlipayZftStore) {
                    $msg = '通道未开通';
                    return [
                        'status' => 2,
                        'message' => $msg
                    ];

                }


                $data['code'] = $auth_code;
                $data['config'] = $config;
                $data['notify_url'] = $notify_url;
                $data['alipay_account'] = $store->alipay_account;
                $data['smid'] = $smid;
                $data['SettleModeType'] = $AlipayZftStore->SettleModeType;
                $data['card_alias_no'] = $AlipayZftStore->card_alias_no;

                //扫一扫分期
                if ($auth_code) {
                    $out_trade_no = 'fq_scan' . date('YmdHis', time()) . $merchant_id . rand(10000, 99999);
                    $data['out_trade_no'] = $out_trade_no;
                    //入库参数
                    $data_insert['ways_type'] = 16001;
                    $data_insert['ways_type_desc'] = '扫一扫分期';
                    $data_insert['ways_source'] = 'alipay';
                    $data_insert['ways_source_desc'] = '支付宝';
                    $data_insert['out_trade_no'] = $out_trade_no;


                    $insert_re = AlipayHbOrder::create($data_insert);

                    if (!$insert_re) {
                        return json_encode([
                            'status' => 2,
                            'message' => '订单未入库'
                        ]);
                    }

                    //转出入库
                    if ($hb_fq_sxf_z > 0) {
                        //结算入库
                        $updatedata = [
                            'trade_no' => '',
                            'user_id' => $tg_user_id,
                            'config_id' => $config_id,
                            'trans_out' => $config->alipay_pid,
                            'order_settle_amount' => $hb_fq_sxf_z,
                            'store_id' => $store_id,
                            'out_trade_no' => $out_trade_no,
                            'total_amount' => $total_amount,
                            'status' => '0',
                            'status_desc' => '等待支付',
                        ];


                        $this->insert_settle_order($updatedata);
                    }

                    if ($StorePayWay->pcredit == "00") {
                        $disable_pay_channels = 'credit_group';//禁用信用方式
                        $data['disable_pay_channels'] = $disable_pay_channels;
                    }

                    $return_array = $pay_obj->zft_scan_pay($data);
                    if ($return_array['status'] == 1) {
                        AlipayHbOrder::where('out_trade_no', $out_trade_no)->update(
                            [
                                'trade_no' => $return_array['trade_no'],
                                'buyer_id' => $return_array['buyer_id'],
                                'buyer_logon_id' => $return_array['buyer_logon_id'],
                                'pay_status_desc' => '支付成功',
                                'pay_status' => 1,
                            ]);

                        //支付后
                        $gmt_payment = $return_array['pay_time'];

                        return json_encode([
                            'status' => 1,
                            'pay_status' => '1',
                            'message' => '支付成功',
                            'data' => [
                                'out_trade_no' => $out_trade_no,
                                'ways_type' => $data_insert['ways_type'],
                                'ways_source' => $data_insert['ways_source'],
                                'total_amount' => $total_amount,
                                'pay_amount' => $total_amount,
                                'store_id' => $store_id,
                                'store_name' => $store_name,
                                'config_id' => $config_id,
                                'pay_time' => $gmt_payment,
                                'ways_source_desc' => '花呗分期',
                            ]
                        ]);


                    }

                    if ($return_array['status'] == 3) {

                        return json_encode([
                            'status' => 1,
                            'pay_status' => '2',
                            'message' => '正在支付',
                            'data' => [
                                'out_trade_no' => $out_trade_no,
                                'ways_type' => $data_insert['ways_type'],
                                'ways_source' => $data_insert['ways_source'],
                                'total_amount' => $total_amount,
                                'pay_amount' => $total_amount,
                                'store_id' => $store_id,
                                'store_name' => $store_name,
                                'config_id' => $config_id,
                            ]
                        ]);
                    }


                    //其他状态
                    return json_encode($return_array);


                } else {
                    $out_trade_no = 'fq_qr' . date('YmdHis', time()) . $merchant_id . rand(10000, 99999);
                    $data['out_trade_no'] = $out_trade_no;

                    if ($StorePayWay->credit == "00") {
                        $disable_pay_channels = 'credit_group';//禁用信用方式
                        $data['disable_pay_channels'] = $disable_pay_channels;
                    }

                    $return = $pay_obj->zft_qr_pay($data);
                    $return_aray = json_decode($return, true);
                    if ($return_aray['status'] == 1) {
                        //入库参数
                        $data_insert['ways_type'] = 16001;
                        $data_insert['ways_type_desc'] = '固定二维码分期';
                        $data_insert['ways_source'] = 'alipay';
                        $data_insert['ways_source_desc'] = '支付宝';
                        $data_insert['out_trade_no'] = $out_trade_no;


                        $insert_re = AlipayHbOrder::create($data_insert);

                        if (!$insert_re) {
                            return json_encode([
                                'status' => 2,
                                'message' => '订单未入库'
                            ]);
                        }

                        //转出入库
                        if ($hb_fq_sxf_z > 0) {
                            //结算入库
                            $updatedata = [
                                'trade_no' => '',
                                'config_id' => $config_id,
                                'order_settle_amount' => $hb_fq_sxf_z,
                                'store_id' => $store_id,
                                'trans_out' => $config->alipay_pid,
                                'user_id' => $tg_user_id,
                                'out_trade_no' => $out_trade_no,
                                'total_amount' => $total_amount,
                                'status' => '0',
                                'status_desc' => '等待支付',
                            ];
                            $this->insert_settle_order($updatedata);
                        }
                    }
                }


                return $return;


            }


        } catch (\Exception $exception) {
            Log::info('花呗分期报错');
            Log::info($exception);
            $info = $exception->getMessage();
            return json_encode([
                'status' => 2,
                'message' => $info
            ]);
        }

    }


    //查询花呗分期服务费多少因该转出多少钱
    public function hb_query_rate($data, $AlipayHbrate)
    {
        try {
            $hb_fq_seller_percent = $data['hb_fq_seller_percent'];
            $shop_price = $data['shop_price'];
            $hb_fq_num = $data['hb_fq_num'];
            $xy_ra_3 = 2.3;
            $xy_ra_6 = 4.5;
            $xy_ra_12 = 7.5;

            $base_ra_3 = 2.3;
            $base_ra_6 = 4.5;
            $base_ra_12 = 7.5;


            //商户承担
            if ($hb_fq_seller_percent == '100') {
                $xy_ra_3 = 1.8;
                $base_ra_3 = 1.8;
            }
            //商户设置的费率
            if ($AlipayHbrate) {
                $xy_ra_3 = $AlipayHbrate->hb_fq_num_3;
                $xy_ra_6 = $AlipayHbrate->hb_fq_num_6;
                $xy_ra_12 = $AlipayHbrate->hb_fq_num_12;
            }


            //用户承担
            if ($hb_fq_seller_percent == "0") {
                $fqfwf_all_3 = ($xy_ra_3 * $shop_price) / 100;//界面显示总服务费
                $total_amount_3 = $fqfwf_all_3 + $shop_price;//界面显示总付款金额
                $total_amount_3_h = ($fqfwf_all_3 + $shop_price) / 3;//每期还款
                $pay_total_amount_3 = $total_amount_3 / (1 + ($base_ra_3 / 100));//传给支付宝
                $hb_fq_sxf_3 = $pay_total_amount_3 - $shop_price;//转出来的部分


                $fqfwf_all_6 = ($xy_ra_6 * $shop_price) / 100;//界面显示总服务费
                $total_amount_6 = $fqfwf_all_6 + $shop_price;//界面显示总付款金额
                $total_amount_6_h = ($fqfwf_all_6 + $shop_price) / 6;//每期还款
                $pay_total_amount_6 = $total_amount_6 / (1 + ($base_ra_6 / 100));//传给支付宝
                $hb_fq_sxf_6 = $pay_total_amount_6 - $shop_price;//转出来的部分

                $fqfwf_all_12 = ($xy_ra_12 * $shop_price) / 100;//界面显示总服务费
                $total_amount_12 = $fqfwf_all_12 + $shop_price;//界面显示总付款金额
                $total_amount_12_h = ($fqfwf_all_12 + $shop_price) / 12;//每期还款
                $pay_total_amount_12 = $total_amount_12 / (1 + ($base_ra_12 / 100));//传给支付宝
                $hb_fq_sxf_12 = $pay_total_amount_12 - $shop_price;//转出来的部分

            } else {

                $fqfwf_all_3 = ($xy_ra_3 * $shop_price) / 100;//界面显示总服务费
                $total_amount_3 = $fqfwf_all_3 + $shop_price;//界面显示总付款金额
                $total_amount_3_h = ($fqfwf_all_3 + $shop_price) / 3;//每期还款
                $pay_total_amount_3 = $shop_price;//传给支付宝
                $hb_fq_sxf_3 = $fqfwf_all_3 - ($shop_price * $base_ra_3) / 100;//转出来的部分


                $fqfwf_all_6 = ($xy_ra_6 * $shop_price) / 100;//界面显示总服务费
                $total_amount_6 = $fqfwf_all_6 + $shop_price;//界面显示总付款金额
                $total_amount_6_h = ($fqfwf_all_6 + $shop_price) / 6;//每期还款
                $pay_total_amount_6 = $shop_price;//传给支付宝
                $hb_fq_sxf_6 = $fqfwf_all_6 - ($shop_price * $base_ra_6) / 100;//转出来的部分

                $fqfwf_all_12 = ($xy_ra_12 * $shop_price) / 100;//界面显示总服务费
                $total_amount_12 = $fqfwf_all_12 + $shop_price;//界面显示总付款金额
                $total_amount_12_h = ($fqfwf_all_12 + $shop_price) / 12;//每期还款
                $pay_total_amount_12 = $shop_price;//传给支付宝
                $hb_fq_sxf_12 = $fqfwf_all_12 - ($shop_price * $base_ra_12) / 100;//转出来的部分

            }


            if ($hb_fq_num == 3) {
                $fq_data = [
                    'hb_fq_num' => 3,
                    'hb_fq_seller_percent' => $hb_fq_seller_percent,
                    'shop_price' => $shop_price,
                    'hb_mq_h' => number_format($total_amount_3_h, 2, '.', ''),
                    'hb_fq_sxf' => number_format($fqfwf_all_3, 2, '.', ''),
                    'total_amount' => number_format($total_amount_3, 2, '.', ''),
                    'hb_fq_sxf_z' => $hb_fq_sxf_3,
                    'pay_total_amount' => $pay_total_amount_3,
                    'xy_rate' => $xy_ra_3
                ];
            } elseif ($hb_fq_num == 6) {
                $fq_data = [
                    'hb_fq_num' => 6,
                    'hb_fq_seller_percent' => $hb_fq_seller_percent,
                    'shop_price' => $shop_price,
                    'hb_mq_h' => number_format($total_amount_6_h, 2, '.', ''),
                    'hb_fq_sxf' => number_format($fqfwf_all_6, 2, '.', ''),
                    'total_amount' => number_format($total_amount_6, 2, '.', ''),
                    'hb_fq_sxf_z' => $hb_fq_sxf_6,
                    'pay_total_amount' => $pay_total_amount_6,
                    'xy_rate' => $xy_ra_6


                ];
            } else {
                $fq_data = [
                    'hb_fq_num' => 12,
                    'hb_fq_seller_percent' => $hb_fq_seller_percent,
                    'shop_price' => $shop_price,
                    'hb_mq_h' => number_format($total_amount_12_h, 2, '.', ''),
                    'hb_fq_sxf' => number_format($fqfwf_all_12, 2, '.', ''),
                    'total_amount' => number_format($total_amount_12, 2, '.', ''),
                    'hb_fq_sxf_z' => $hb_fq_sxf_12,
                    'pay_total_amount' => $pay_total_amount_12,
                    'xy_rate' => $xy_ra_12
                ];
            }

            $data = [
                'status' => 1,
                'message' => '数据返回成功',
                'data' => $fq_data
            ];

            return $data;


        } catch (\Exception $exception) {
            $data = [
                'status' => 2,
                'message' => $exception->getMessage(),
            ];
            return $data;
        }


    }


    //方法
    public function ways_source(Request $request)
    {
        try {
            $merchant = $this->parseToken();
            $merchant_id = $merchant->merchant_id;
            $MerchantStore = MerchantStore::where('merchant_id', $merchant_id)
                ->orderBy('created_at', 'asc')
                ->first();
            $store_id = '';
            if ($MerchantStore) {
                $store_id = $MerchantStore->store_id;

            }

            $data = [];

            //官方
            $StorePayWay = StorePayWay::where('store_id', $store_id)
                ->where('status', 1)
                ->where('ways_type', 1000)
                ->select('id')
                ->first();

            if ($StorePayWay) {
                $data[] =
                    [
                        'ways_source' => 'alipay',
                        'ways_source_desc' => '支付宝-当面付'
                    ];
            }

            //网商
            $StorePayWay = StorePayWay::where('store_id', $store_id)
                ->where('status', 1)
                ->where('ways_type', 3001)
                ->select('id')
                ->first();
            if ($StorePayWay) {
                $data[] = [
	        	'ways_source' => 'mybank',
	                'ways_source_desc' => '支付宝-快钱'
            	];
            }

            //zft
            $StorePayWay = StorePayWay::where('store_id', $store_id)
                ->where('status', 1)
                ->where('ways_type', 16001)
                ->where('company', 'zft')
                ->select('id')
                ->first();

            if ($StorePayWay) {
                $data[] =
                    [
                        'ways_source' => 'zft',
                        'ways_source_desc' => '支付宝-ZFT'
                    ];
            }

            return json_encode(
                [
                    'status' => 1,
                    'data' => $data
                ]
            );
        } catch (\Exception $exception) {
            return json_encode(['status' => 2, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }
    }


    //查询花呗分期的费率
    public function hbrate(Request $request)
    {
        try {
            $user = $this->parseToken();
            $merchant_id = $user->merchant_id;
            $type = $request->get('hb_fq_seller_percent', 100);//客户端已经不传了 默认商户承担
            $hb_fq_num = $request->get('hb_fq_num');
            $MerchantStore = MerchantStore::where('merchant_id', $merchant_id)
                ->orderBy('created_at', 'asc')
                ->first();
            $store_id = '';
            if ($MerchantStore) {
                $store_id = $MerchantStore->store_id;

            }
            $AlipayHbrate = AlipayHbrate::where('store_id', $store_id)->first();
            //商户承担
            if ($type == 100) {
                $hb_fq_num_3 = 0;
                $hb_fq_num_6 = 0;
                $hb_fq_num_12 = 0;
                //商户自己设置
//                if ($AlipayHbrate) {
//                    $hb_fq_num_3 = $AlipayHbrate->hb_fq_num_3 / 100;
//                    $hb_fq_num_6 = $AlipayHbrate->hb_fq_num_6 / 100;
//                    $hb_fq_num_12 = $AlipayHbrate->hb_fq_num_12 / 100;
//                    $hb_fq_num_24 = $AlipayHbrate->hb_fq_num_24 / 100;
//                }
//               // 用户承担
            } else {
                $hb_fq_num_3 = 0.023;
                $hb_fq_num_6 = 0.045;
                $hb_fq_num_12 = 0.075;
                //商户自己设置
                if ($AlipayHbrate) {
                    $hb_fq_num_3 = $AlipayHbrate->hb_fq_num_3 / 100;
                    $hb_fq_num_6 = $AlipayHbrate->hb_fq_num_6 / 100;
                    $hb_fq_num_12 = $AlipayHbrate->hb_fq_num_12 / 100;
                }
            }


            //官方2.30%
            if ((int)$hb_fq_num == 3) {
                return json_encode(['status' => 1, 'data' => [
                    'rate' => $hb_fq_num_3,
                ]]);
            }
            //官方4.5%
            if ((int)$hb_fq_num == 6) {
                return json_encode(['status' => 1, 'data' =>
                    ['rate' => $hb_fq_num_6,
                    ]]);
            }
            // 官方7.5%
            if ((int)$hb_fq_num == 12) {
                return json_encode(['status' => 1, 'data' => [
                    'rate' => $hb_fq_num_12,
                ]]);
            }


            return json_encode(['status' => 2, 'message' => "参数填写不正确"]);


        } catch (\Exception $exception) {
            return json_encode(['status' => 2, 'message' => $exception->getMessage()]);

        }
    }


    //商户花呗分期数查询
    public function hb_fq_num(Request $request)
    {
        try {
            $merchant = $this->parseToken();
            $merchant_id = $merchant->merchant_id;
            $MerchantStore = MerchantStore::where('merchant_id', $merchant_id)
                ->orderBy('created_at', 'asc')
                ->first();
            $store_id = '';
            if ($MerchantStore) {
                $store_id = $MerchantStore->store_id;

            }
            $AlipayHbrate = AlipayHbrate::where('store_id', $store_id)->first();
            if ($AlipayHbrate) {
                $hb_fq_num_3 = [];
                if ($AlipayHbrate->hb_fq_num_3_status == '01') {
                    $hb_fq_num_3 = [
                        'hb_fq_num' => 3,
                        'hb_fq_rate' => $AlipayHbrate->hb_fq_num_3,
                        'hb_fq_num_desc' => '3期'
                    ];
                }
                $hb_fq_num_6 = [];
                if ($AlipayHbrate->hb_fq_num_6_status == '01') {
                    $hb_fq_num_6 = [
                        'hb_fq_num' => 6,
                        'hb_fq_rate' => $AlipayHbrate->hb_fq_num_6,
                        'hb_fq_num_desc' => '6期'
                    ];
                }
                $hb_fq_num_12 = [];
                if ($AlipayHbrate->hb_fq_num_12_status == '01') {
                    $hb_fq_num_12 = [
                        'hb_fq_num' => 12,
                        'hb_fq_rate' => $AlipayHbrate->hb_fq_num_12,
                        'hb_fq_num_desc' => '12期'
                    ];
                }

                $data = [$hb_fq_num_3, $hb_fq_num_6, $hb_fq_num_12];
                $data1 = [];

                foreach ($data as $k => $v) {
                    if (count($v)) {
                        $data1[$k] = $v;
                    }
                    continue;
                }
                $data2 = [];
                foreach ($data1 as $k => $v) {
                    $data2[] = $v;
                }

                $data = array_filter($data2);

            } else {
                $data = [
                    [
                        'hb_fq_num' => 3,
                        'hb_fq_rate' => 1.8,
                        'hb_fq_num_desc' => '3期'
                    ],
                    [
                        'hb_fq_num' => 6,
                        'hb_fq_rate' => 4.5,
                        'hb_fq_num_desc' => '6期'
                    ],
                    [
                        'hb_fq_num' => 12,
                        'hb_fq_rate' => 7.5,
                        'hb_fq_num_desc' => '12期'
                    ]

                ];
            }


            return json_encode(['status' => 1, 'data' => $data]);

        } catch (\Exception $exception) {
            return json_encode(['status' => 2, 'message' => $exception->getMessage()]);

        }
    }


    //查询官方花呗分期的费率
    public function gf_hbrate($type, $hb_fq_num)
    {
        if ($type == 100) {
            $hb_fq_num_3 = 1.8;
        } else {
            $hb_fq_num_3 = 2.3;
        }
	
        $hb_fq_num_6 = 4.5;
        $hb_fq_num_12 = 7.5;
        $hb_fq_num_24 = 12.5;

        //官方2.30%
        if ((int)$hb_fq_num == 3) {
            $rete = $hb_fq_num_3;
        }
	
        //官方4.5%
        if ((int)$hb_fq_num == 6) {
            $rete = $hb_fq_num_6;
        }
	
        // 官方7.5%
        if ((int)$hb_fq_num == 12) {
            $rete = $hb_fq_num_12;
        }

        return $rete;
    }


    //得到传到支付宝的价格
    public function ali_price($store_id, $AlipayHbrate, $shop_price, $hb_fq_num)
    {
        //官方的费率
        $gf_ra_3 = 2.3;
        $gf_ra_6 = 4.5;
        $gf_ra_12 = 7.5;
        $gf_ra_24 = 12.5;

        //默认官方
        $xy_ra_3 = 2.3;
        $xy_ra_6 = 4.5;
        $xy_ra_12 = 7.5;
        $xy_ra_24 = 12.5;
        //商户自己设置
        if ($AlipayHbrate) {
            $xy_ra_3 = $AlipayHbrate->hb_fq_num_3;
            $xy_ra_6 = $AlipayHbrate->hb_fq_num_6;
            $xy_ra_12 = $AlipayHbrate->hb_fq_num_12;
            $xy_ra_24 = $AlipayHbrate->hb_fq_num_24;
        }

        //2.30%
        if ((int)$hb_fq_num == 3) {
            $xy_money = (($xy_ra_3 * $shop_price) / 100) + $shop_price;//想用的收款
            $a = (100 + $gf_ra_3);
            $ali_money = $xy_money * (100 / (100 + $gf_ra_3));
        }
        //4.5%
        if ((int)$hb_fq_num == 6) {
            $xy_money = (($xy_ra_6 * $shop_price) / 100) + $shop_price;//想用的收款
            $ali_money = $xy_money * (100 / (100 + $gf_ra_6));
        }
        // 7.5%
        if ((int)$hb_fq_num == 12) {
            $xy_money = (($xy_ra_12 * $shop_price) / 100) + $shop_price;//想用的收款
            $ali_money = $xy_money * (100 / (100 + $gf_ra_12));
        }


        return number_format($ali_money, 2, ".", "");
    }


    //得到门店设置想用的费率
    public function xy_rate($store_id, $AlipayHbrate, $hb_fq_num, $hb_fq_seller_percent = 0)
    {
        if ($hb_fq_seller_percent == 0) {
            $xy_ra_3 = 2.3;
        } else {
            $xy_ra_3 = 1.8;
        }

        $xy_ra_6 = 4.5;
        $xy_ra_12 = 7.5;

        //2.30%
        if ((int)$hb_fq_num == 3) {
            $rate = $xy_ra_3;
        }
        //4.5%
        if ((int)$hb_fq_num == 6) {
            $rate = $xy_ra_6;
        }
        // 7.5%
        if ((int)$hb_fq_num == 12) {
            $rate = $xy_ra_12;
        }

        return $rate;
    }


    //直付通费率
    public function zft_rate($store_id, $hb_fq_num, $hb_fq_seller_percent = 0)
    {
        if ($hb_fq_seller_percent == 0) {
            $xy_ra_3 = 2.3;
        } else {
            $xy_ra_3 = 1.8;
        }

        $xy_ra_6 = 4.5;
        $xy_ra_12 = 7.5;

        //2.30%
        if ((int)$hb_fq_num == 3) {
            $rate = $xy_ra_3;
        }
	
        //4.5%
        if ((int)$hb_fq_num == 6) {
            $rate = $xy_ra_6;
        }
	
        // 7.5%
        if ((int)$hb_fq_num == 12) {
            $rate = $xy_ra_12;
        }

        return $rate;
    }


    //查询支付宝的订单状态
    public function AlipayTradePayQuery($out_trade_no, $app_auth_token, $configs)
    {
        $aop = new AopClient();
        $aop->rsaPrivateKey = $configs->rsa_private_key;
        $aop->appId = $configs->app_id;
        $aop->method = 'alipay.trade.query';

        $aop->signType = "RSA2";//升级算法
        $aop->gatewayUrl = $configs->alipay_gateway;
        $aop->format = "json";
        $aop->charset = "GBK";
        $aop->version = "2.0";
        $requests = new AlipayTradeQueryRequest();
        $requests->setBizContent("{" .
            "    \"out_trade_no\":\"" . $out_trade_no . "\"" .
            "  }");
        $result = $aop->execute($requests, '', $app_auth_token);
	
        return $result;
    }


    //支付宝取消接口
    public function AlipayTradePayCancel($out_trade_no, $app_auth_token, $configs)
    {
        $aop = new AopClient();
        $aop->rsaPrivateKey = $configs->rsa_private_key;
        $aop->appId = $configs->app_id;
        $aop->method = 'alipay.trade.cancel';

        $aop->signType = "RSA2";//升级算法
        $aop->gatewayUrl = $configs->alipay_gateway;
        $aop->format = "json";
        $aop->charset = "GBK";
        $aop->version = "2.0";
        $requests = new AlipayTradeCancelRequest();
        $requests->setBizContent("{" .
            "    \"out_trade_no\":\"" . $out_trade_no . "\"" .
            "  }");
        $result = $aop->execute($requests, '', $app_auth_token);
	
        return $result;
    }


}
